<template>
    <section class="todoapp">
           <TodoHeader @add="addFn" :arr="list"></TodoHeader>
           <TodoMain :arr="showList" @del="delFn"></TodoMain>
           <TodoFooter :arr="list" @delShow="delShowFn" @changeType="changeTypeFn"></TodoFooter>
    </section>
</template>

<script>
// 导入组件并注册使用
	import TodoHeader from './components/TodoHeader.vue'
	import TodoMain from './components/TodoMain.vue'
	import TodoFooter from './components/TodoFooter.vue'
	// 导入样式
	import './styles/base.css'
	import './styles/index.css'

export default {
    data() {
        return {
            list:JSON.parse(localStorage.getItem('todos')) || [],
            type: 'one'    // 默认显示全部数据
        }
    },

    methods: {
        // todo ==== 删除对应任务数据
         delFn(id){
             this.list = this.list.filter(item => item.id !== id)
         },

        // todo ==== 新增对应任务数据
         addFn(name){
            this.list.unshift({
                id: +new Date(),
                name,
                isDone: false,
            })
         },
         
        // todo ==== 点击按钮清空已完成
         delShowFn(){
             this.list = this.list.filter(item => !item.isDone)   
         },

         changeTypeFn(type){
             this.type = type
         }
    },

     computed: {
         showList(){
              if(this.type === 'two'){
                  return this.list.filter(item => !item.isDone)
              }else if(this.type === 'three') {
                  return this.list.filter(item => item.isDone)                
              }else{
                 return this.list
              }
         }  
     },

     watch: {
        // todo ==== 数据存为本地存储
         list: {
             deep: true,
             handler(newVal){
                localStorage.setItem('todos', JSON.stringify(newVal))
             }
         }
     },

    components: {
          TodoHeader,
          TodoMain,
          TodoFooter
    }
}
</script>
